package com.runen.wnhz.runen.ui.activity.mine;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.MyOrderBean;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.Constants;
import com.runen.wnhz.runen.common.utils.GlideCircleTransform;
import com.runen.wnhz.runen.common.utils.JumpUtlis;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.MineBean;
import com.runen.wnhz.runen.data.entity.MineFragmentBean;
import com.runen.wnhz.runen.data.entity.PersonalEntity;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.ui.ActivityManager;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.MineFragmentAdapter;
import com.runen.wnhz.runen.ui.fragment.BaseFragment;
import com.runen.wnhz.runen.widget.TitleBuilder;

import java.io.IOException;
import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import io.rong.imkit.RongIM;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;


/**
 * Created by Administrator on 2018-04-08.
 */

public class MineFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    public static final String TAG = "MineFragment";

    private ListView lv_mine_list;

    private MineFragmentAdapter adapter;

    private ArrayList<MineFragmentBean> mDatas = new ArrayList<>();

    private View mHeadView;

    private TextView tv_nick_name;

    private ImageView iv_mine_touxiang;

    private LinearLayout mine_head_image;

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }

    @Override
    protected int getLayoutView() {
        return R.layout.mine_fragment_layout;
    }

    @Override
    public void initUiAndListener(View view) {
        StatusBarCompatUtils.getInstance().TranslucentStatusBar((Activity) getContext(), R.color.person);
        initHeadView();
        initView(view);
        initDatas();
        initAdapter();

        lv_mine_list.addHeaderView(mHeadView);
        lv_mine_list.setAdapter(adapter);
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        setToolBarVisible(View.GONE);
    }

    private void initAdapter() {
        adapter = new MineFragmentAdapter(mContext, mDatas);
    }

    private void initDatas() {

        MineFragmentBean mineFragmentBean1 = new MineFragmentBean("我的测评", R.mipmap.icon_wodeceping);
        MineFragmentBean mineFragmentBean2 = new MineFragmentBean("我的课程", R.mipmap.icon_wodekecheng);
        MineFragmentBean mineFragmentBean3 = new MineFragmentBean("我的收藏", R.mipmap.icon_wodeshoucang);
        MineFragmentBean mineFragmentBean4 = new MineFragmentBean("我的余额", R.mipmap.icon_wodeyue);
        MineFragmentBean mineFragmentBean5 = new MineFragmentBean("消息中心", R.mipmap.icon_xiaoxizhongxin);
        MineFragmentBean mineFragmentBean6 = new MineFragmentBean("我的订单", R.mipmap.icon_wodedingdan);
        MineFragmentBean mineFragmentBean7 = new MineFragmentBean("收货地址", R.mipmap.icon_shouhuodizhi);
        MineFragmentBean mineFragmentBean8 = new MineFragmentBean("个人中心", R.mipmap.icon_gerenzhongxin);
        MineFragmentBean mineFragmentBean9 = new MineFragmentBean("意见反馈", R.mipmap.icon_yijianfankui);
        MineFragmentBean mineFragmentBean10 = new MineFragmentBean("账号设置", R.mipmap.icon_zhanghaoshezhi);
        MineFragmentBean mineFragmentBean11 = new MineFragmentBean("账户注销", R.mipmap.icon_zhanghaoshezhi);

        mDatas.add(mineFragmentBean1);
        mDatas.add(mineFragmentBean2);
        mDatas.add(mineFragmentBean3);
        mDatas.add(mineFragmentBean4);
        mDatas.add(mineFragmentBean5);
        mDatas.add(mineFragmentBean6);
        mDatas.add(mineFragmentBean7);
        mDatas.add(mineFragmentBean8);
        mDatas.add(mineFragmentBean9);
        mDatas.add(mineFragmentBean10);
        mDatas.add(mineFragmentBean11);
    }

    private void initHeadView() {
        mHeadView = LayoutInflater.from(mContext).inflate(R.layout.mine_fragment_head_view, null);
    }

    private void initView(View view) {
        lv_mine_list = view.findViewById(R.id.lv_mine_list);
        mine_head_image = mHeadView.findViewById(R.id.mine_head_image);
        tv_nick_name = mHeadView.findViewById(R.id.tv_nick_name);
        iv_mine_touxiang = mHeadView.findViewById(R.id.iv_mine_touxiang);
        lv_mine_list.setOnItemClickListener(this);
        updateHead();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateHead();
    }

    private void updateHead() {
        UserBean requestUser = ACacheUtlis.getInstance().getReqeustUser(getContext());
        if (requestUser == null) {
            mine_head_image.setOnClickListener(this);
            iv_mine_touxiang.setImageResource(R.mipmap.icon_touxiang);
            tv_nick_name.setText("点击登录");
        } else {
            tv_nick_name.setText(requestUser.getUsername());
            Glide.with(getContext()).load(requestUser.getHead_img()).centerCrop().transform(new GlideCircleTransform(getContext())).into(iv_mine_touxiang);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 1:
                /*我的测评*/
                JumpUtlis.getInstance().jumpActivity(getContext(), MyTestActivity.class, true);
                break;
            case 2:
                /*我的课程*/
                JumpUtlis.getInstance().jumpActivity(getContext(), ClassCenterActivity.class, true);
                break;
            case 3:
                /*我的收藏*/
                JumpUtlis.getInstance().jumpActivity(getContext(), MyCollectionActivity.class, true);
                break;
            case 4:
                /*我的余额*/
                JumpUtlis.getInstance().jumpActivity(getContext(), BalanceActivity.class, true);
                break;
            case 5:
                /*消息中心*/
                JumpUtlis.getInstance().jumpActivity(getContext(), MessageCenterActivity.class, true);
                break;
            case 6:
                /*我的订单*/
                JumpUtlis.getInstance().jumpActivity(getContext(), MyOrderActivity.class, true);
                break;
            case 7:
                /*收货地址*/
                JumpUtlis.getInstance().jumpActivity(getContext(), ReceivingAddressActivity.class, true);
                break;
            case 8:
                /*个人中心*/
                JumpUtlis.getInstance().jumpActivity(getContext(), PersonalCenterActivity.class, true);
                break;
            case 9:
                /*意见反馈*/
                JumpUtlis.getInstance().jumpActivity(getContext(), FeedbackActivity.class, true);
                break;
            case 10:
                /*账号设置*/
                JumpUtlis.getInstance().jumpActivity(getContext(), AccountSettingActivity.class, true);
                break;
            case 11:
                /*账户注销*/
                UserBean requestUser = ACacheUtlis.getInstance().getReqeustUser(getContext());
                if (requestUser == null) {
                    iv_mine_touxiang.setImageResource(R.mipmap.icon_touxiang);
                    tv_nick_name.setText("点击登录");
                } else {
                gotoCancelUser(requestUser.getToken());
                }
                break;
            default:
                break;
        }
    }

    public void gotoCancelUser(String token){

        if(token  != null) {
            FormBody formBody = new FormBody.Builder().add("token",token).build();
            System.out.println("tttttttttoken == " + token);
            Request.Builder builder = new Request.Builder().url(NetUtils.User_CANCELUser).post(formBody);
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(builder.build());
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                handleUserCollectionData(response);
                            } catch (IOException e) {
                                e.printStackTrace();
                                ToastUtil.showToast("数据请求异常");
                            }
                        }
                    });
                }
            });
        }
    }

    private void handleUserCollectionData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            final String json = responseBody.string();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MineBean rebackVal = new Gson().fromJson(json, MineBean.class);
                    String re = rebackVal.getRe();
                    if (re.equals("1")){

                        JPushInterface.deleteAlias(getContext(),Constants.JPUSH_SEQUEENS);
                        ACacheUtlis.getInstance().isLogin(getContext(), "false");
                        ACacheUtlis.getInstance().IsRequstUser(getContext(), "", "", "","");
                        ToastUtil.showToast(re);
                        RongIM.getInstance().logout();
                        JumpUtlis.getInstance().jumpActivity(getActivity(), LoginForPersonalActivity.class);
                        ActivityManager.getAppManager().finishActivity(getActivity());
                    }else{
                        ToastUtil.showToast(rebackVal.getInfo());
                    }
                }
            });

        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mine_head_image:
                JumpUtlis.getInstance().jumpActivity(getContext(), LoginForPersonalActivity.class, false);
                break;
        }

    }

    @Override
    public void onTitleButtonClicked(TitleBuilder.TitleButton clicked) {

    }
}
